package com.mingqijia.gassafety.job.hangzhou.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.hangzhou.entity.CityDevice;
import com.mingqijia.gassafety.db.hangzhou.entity.CityProduct;
import com.mingqijia.gassafety.db.hangzhou.mapper.CityDeviceMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.job.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.job.hangzhou.request.RegisterCityDevice;
import com.mingqijia.gassafety.job.hangzhou.response.HzResponse;
import com.mingqijia.gassafety.job.hangzhou.service.CityDeviceService;
import com.mingqijia.gassafety.job.hangzhou.service.CityProductService;
import com.mingqijia.gassafety.job.hangzhou.service.HangZhouService;
import com.mingqijia.gassafety.job.request.ConsoleSkSupplierListRequest;
import com.mingqijia.gassafety.job.response.ConsoleSkSupplierListResponse;
import com.mingqijia.gassafety.job.service.EquipmentService;
import com.mingqijia.gassafety.job.service.cmp.EquipmentCmpService;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.HangZhouConst;
import com.mingqijia.gassafety.shared.utils.CoordinateTransformer;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: gassafety
 * @description:
 * @author: Mr.Wang
 * @create: 2022-11-30 18:10
 **/
@Service
@Slf4j
public class CityDeviceServiceImpl extends ServiceImpl<CityDeviceMapper, CityDevice> implements CityDeviceService {
    @Autowired
    RedisCacheExt redisUtil;

    @Value("${gassafety.hangzhou.yhSpId}")
    private String hangzhouSpId;

    @Autowired
    CityDeviceService cityDeviceService;

    @Autowired
    EquipmentService equipmentService;

    @Autowired
    CityProductService cityProductService;

    @Autowired
    DtuMapper dtuMapper;

    @Autowired
    ConfigureHolder holder;

    @Autowired
    HangZhouService hangZhouService;

    @Autowired
    private EquipmentCmpService equipmentCmpService;


    private static int responseCode = 200;


    @Override
    public void registerCityDevice() {
        //存入本地数据
        ArrayList<CityDevice> localCityDeviceList = new ArrayList<>();
        //获取所有绑定客户的设备
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getSpId,hangzhouSpId)
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .ne(Dtu::getConsumerId,0);
        List<Dtu> allDtuList = equipmentService.list(dtuQueryWrapper);

        //已注册的设备集合
        QueryWrapper<CityDevice> cityDeviceQueryWrapper = new QueryWrapper<>();
        cityDeviceQueryWrapper.lambda().eq(CityDevice::getIsDeleted,Constants.IS_DELETED_FALSE)
                .eq(CityDevice::getSpId,hangzhouSpId);
        List<CityDevice> cityDeviceList = cityDeviceService.list(cityDeviceQueryWrapper);
        List<String> cityImeiList = cityDeviceList.stream().map(CityDevice::getDeviceName).collect(Collectors.toList());

        //如果该imei不在CityDevice表中
        ArrayList<String> imeiList = new ArrayList<>();
        //本次注册的设备id集合
        for (Dtu dtu : allDtuList) {
            if (!cityImeiList.contains(dtu.getIMEI())){
                imeiList.add(dtu.getIMEI());
            }
        }
        //没有新的需要注册设备
        if (CollectionUtil.isEmpty(imeiList)){
            return;
        }
        log.info("需要注册的设备imei集合: {}", imeiList.toString());
        //查询所有productKey
        LambdaQueryWrapper<CityProduct> cityProductLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cityProductLambdaQueryWrapper.eq(CityProduct::getIsDeleted,Constants.IS_DELETED_FALSE)
                .eq(CityProduct::getSpId,hangzhouSpId);;
        List<CityProduct> cityProductList = cityProductService.list(cityProductLambdaQueryWrapper);
        //查询dtu表并关联客户表
        List<Map<String, Object>> deviceInfoList = dtuMapper.getDeviceInfo(imeiList);

        ConsoleSkSupplierListResponse resp = equipmentCmpService.supplierListRequest();
        List<DictionaryItemRespDTO> equipmentManufacturer = new ArrayList<>();
        if (null != resp && null != resp.getData() && CollectionUtils.isNotEmpty(resp.getData()) ) {
            log.info("结束调用厨房查询厂商接口，返回数据长度：{}", resp.getData().size());
            equipmentManufacturer = resp.getData().stream().map(item -> {
                DictionaryItemRespDTO re = new DictionaryItemRespDTO();
                re.setId(item.getAlarmSystemCode());
                re.setName(item.getMsName());
                re.setDictCode("Equipment_manufacturer");
                re.setValue(item.getAlarmSystemCode());
                re.setDescription(item.getMsName());
                return re;
            }).collect(Collectors.toList());
        }
        for (Map<String, Object> map : deviceInfoList) {
            //获得该设备的厂商
            String manufacturer = map.get("equipment_manufacturer").toString();
            //所有厂商,获得该设备的厂商
//            List<DictionaryItemRespDTO> equipmentManufacturer = holder.getDictionaryByKey("Equipment_manufacturer",hangzhouSpId);

            DictionaryItemRespDTO manufacturerDTO = CollectionUtils.isEmpty(equipmentManufacturer) ? null
            :equipmentManufacturer.stream().filter(e -> e.getValue().equals(manufacturer)).collect(Collectors.toList()).get(0);
            for (CityProduct cityProduct : cityProductList) {
                //必须是已经创建产品的设备类型和产商,才能注册设备
                if (    null != manufacturerDTO
                        && StringUtils.isNotEmpty(manufacturerDTO.getName())
                        && cityProduct.getProductType().equals(map.get("equipment_type").toString())
                        && cityProduct.getEquipmentManufacturer().equals(manufacturerDTO.getName())){
                    log.info("map : {}", map.toString());
                    RegisterCityDevice req = new RegisterCityDevice();
                    req.setProductKey(cityProduct.getProductKey());
                    req.setDeviceName(map.get("iMEI").toString());
                    req.setAlias(map.get("Name")!=null?map.get("Name").toString():"");
                    req.setDescription(map.get("remark")!=null?map.get("remark").toString():"");
                    RegisterCityDevice.DeviceLocation deviceLocation = req.new DeviceLocation();
                    deviceLocation.setAddress(map.get("Address").toString());
                    //进行坐标格式转换
                    double positionLat = Double.parseDouble(map.get("Position_Lat").toString());
                    double positionLon = Double.parseDouble(map.get("Position_Lon").toString());
                    double[] toWGS84 = CoordinateTransformer.transformBD09ToWGS84(positionLon, positionLat);
                    deviceLocation.setLatitude( new BigDecimal(toWGS84[1]));
                    deviceLocation.setLongitude(new BigDecimal( toWGS84[0]));
                    deviceLocation.setCoordinateSystem("WGS_84");
                    req.setDeviceLocation(deviceLocation);
                    //调用接口,成功则存入本地
                    HzResponse hzResponse = hangZhouService.registerCityDevice(req);
                    if(hzResponse.getCode() == responseCode){
                        CityDevice cityDevice = new CityDevice();
                        BeanUtils.copyProperties(req,cityDevice);
                        cityDevice.setSpId(map.get("sp_id").toString());
                        cityDevice.setAddress(map.get("Address").toString());
                        cityDevice.setLatitude(toWGS84[1]);
                        cityDevice.setLongitude(toWGS84[0]);
                        cityDevice.setOrganizationId(HangZhouConst.ORGANIZATION_ID);
                        cityDevice.setCoordinateSystem(req.getDeviceLocation().getCoordinateSystem());
                        localCityDeviceList.add(cityDevice);
                    }
                }
            }
        }
        log.info("注册的设备信息,localCityDeviceList:{}",localCityDeviceList.toString());
        //批量存入
        cityDeviceService.saveBatch(localCityDeviceList);

    }
}
